#!/usr/bin/env bash

set -ex

DIR=$(dirname $(realpath "$0"))

cd $DIR

if [ ! -d "node_modules" ]; then
  pnpm i
fi

cd ..

if [ ! -d "ci" ]; then
  git clone git@github.com:izhenxiang/dist.git ci --depth 1
fi

cd $DIR
CI=$(dirname $DIR)/ci

config=$DIR/src/config/

platform=$(node --input-type=module -e "import mod from '$config/platform.mjs';console.log(mod)")
arch=$(node --input-type=module -e "import mod from '$config/arch.mjs';console.log(mod)")

npx electron ./script/electron.cjs

echo 'export default 0' > src/config/dev.js

pa=$platform-$arch
distdir=$CI/dist/$pa

rm -rf $CI/tmp $distdir

pnpm run build

cp $CI/node/$pa/*.node $CI/tmp
misc/filename_min.coffee

cd $CI

case "$platform" in
  darwin*)  tray=black ;;
  *)        tray=color ;;
esac

cd $CI

cp pkg/tray/$tray/*.png tmp
cp app/package.json tmp
mv tmp $distdir
